import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { mergeConfig } from '../mergeConfig';

import { Modal, Input, Button, Steps, Form, Select, Checkbox, message } from 'antd';

const { Step } = Steps;
const { Option } = Select;

class FieldMerge extends Component{
  state={
    checkedList: [],
    indeterminate: true,
    checkAll: false,
    visible: false,
  }

  selectConfig = value => {//改变数据库连接
    let config = JSON.parse(value);
    if(this.props.inputConfig.databaseType===config.databaseType){
      this.props.setMergeConfig(config);
      console.log("字段合并数据库连接信息",config);
      this.props.getMergeTable(config.databaseType,{id:config.databaseId});
      this.props.clearMergeField();
      this.props.formRef.current.setFieldsValue({mTable:undefined, mName:undefined, mColumnFamily:undefined});
    }
    else{
      message.info('合并组件需和表输入的数据库类型一致');
    }
  }

  onFieldChange = checkedList => {
    this.props.setMergeCheckList(checkedList);
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < this.props.mField.length,
      checkAll: checkedList.length === this.props.mField.length,
    });
  };

  handleClick = () => {
    this.setState({visible:true})
  };

  handleOk = () => {
    this.props.formRef.current.setFieldsValue({mName:this.props.mergeCheckList.length>0?this.props.mergeCheckList:undefined});
    this.setState({visible:false});
  }

  handleCancel = () => {
    this.setState({visible:false});
  }

  onCheckAllChange = e => {
    this.props.setMergeCheckList(e.target.checked ? this.props.mField : []);
    this.setState({
      checkedList: e.target.checked ? this.props.mField : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  handleTableChange = (value) => {
    let dbType = this.props.mConfig.databaseType;
    let id = this.props.mConfig.databaseId;
    let table = value;
    this.props.formRef.current.setFieldsValue({mName:undefined,keyField2:undefined});
    this.props.getMergeField(dbType,{id,table})//mysql、sqlsever、MongoDB、oracle为表->列，hbase为列族->列
  }

  handleHBaseTableChange = (value) => {//选择hbase表后查找列族
    let id = this.props.mConfig.databaseId;
    let table = value;
    this.props.formRef.current.setFieldsValue({mColumnFamily:undefined, mName:undefined,keyField2:undefined});
    this.props.getMergeColumnFamily(id,table);
  }

  renderFormItem = (item) => {//根据不同的数据库连接渲染不同的表输入表单项
    let func = this[`${item.function}`];
    let message = item.message?item.message:"";
    switch(item.type){
      case 'select':
        return <Form.Item label={item.label} name={item.name}
        rules={[{
          required: true,
          message: {message},
        },]}>
          <Select placeholder={item.placeholder} onChange={func}
          showSearch
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }>
            {
              this.props.mTable.map(table => (
                <Option value={table}>{table}</Option>
              ))
            }
          </Select>
        </Form.Item>
      case 'selectColumnFamily':
        return <Form.Item label={item.label} name={item.name}
        rules={[{
          required: true,
          message: {message},
        },]}>
          <Select placeholder={item.placeholder} onChange={func}
          showSearch
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }>
            {
              this.props.mColumnFamily.map(columnFamily => (
                <Option value={columnFamily}>{columnFamily}</Option>
              ))
            }
          </Select>
        </Form.Item>
      case 'fieldSelect': 
        return <Fragment>
          <Form.Item label="字段选择" name="mName"
          rules={[{
            required: true,
            message: '请进行字段选择！',
          },]}>
            <Button type="dashed" onClick={this.handleClick}>字段选择</Button>
          </Form.Item>
          <Modal
            title="字段选择"
            visible={ this.state.visible }
            onOk={ this.handleOk }
            onCancel={ this.handleCancel }
          >
            <div style={{ borderBottom: '1px solid #E9E9E9' }}>
              <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                全选
              </Checkbox>
            </div>
            <br />
            <Form.Item>
              <Checkbox.Group
                options={this.props.mField}
                value={this.props.mergeCheckList}
                onChange={this.onFieldChange}
              />
            </Form.Item>
          </Modal>
        </Fragment>
      default: return null;
    }
  }

  render(){
    return (
      <Fragment>
        <Form.Item label="数据库连接" name="databaseId"
        rules={[{
          required: true,
          message: '请选择数据库连接！',
        },]}>
          <Select placeholder="请选择数据库连接" onChange={this.selectConfig}>
            {
              this.props.briefConfig.map(config => (
                <Option key={config.id} value={JSON.stringify(config)}>{config.configName}</Option>
              ))
            }
          </Select>
        </Form.Item>
        {
          this.props.mConfig?
          mergeConfig(this.props.mConfig.databaseType).formSourceMapping.map(item=>{//inputConfig(databaseType)匹配不同数据库类型对应的表单项
            return this.renderFormItem(item);
          }):null
        }
        {
          this.props.mConfig?
          <Fragment>
            <Form.Item label="连接类型" name="joinTypes"
            rules={[{
              required: true,
              message: '请选择连接类型！',
            },]}>
              <Select placeholder="请选择连接类型">
                <Select.Option value="0" >内连接</Select.Option>
                <Select.Option value="1" >左连接</Select.Option>
                <Select.Option value="2" >右连接</Select.Option>
                <Select.Option value="3" >全连接</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="合并字段1" name="keyField1"
            rules={[{
              required: true,
              message: '请选择合并字段1！',
            },]}>
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择合并字段1"
              >
                {
                  this.props.inputField.map(item => (
                    <Option key={item.fieldName} value={item.fieldName}>{item.fieldName}</Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item label="合并字段2" name="keyField2"
            rules={[{
              required: true,
              message: '请选择合并字段2！',
            },]}>
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择合并字段2"
              >
                {
                  this.props.mergeCheckList?
                  this.props.mergeCheckList.map(field => (
                    <Option key={field} value={field}>{field}</Option>
                  )):
                  this.state.checkedList.map(field => (
                    <Option key={field} value={field}>{field}</Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Fragment>:null
        }
      </Fragment>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    inputField: state.getIn(['createTask','inputField']).toJS(),
    briefConfig: state.getIn(['createTask','briefConfig']).toJS(),
    mField: state.getIn(['createTask','mField']).toJS(),
    mColumnFamily: state.getIn(['createTask','mColumnFamily']).toJS(),
    mTable: state.getIn(['createTask','mTable']).toJS(),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getMergeTable(databaseType,params){
    dispatch(actionCreators.getMergeTableOperation(databaseType,params));
  },
  getMergeField(dbType,params){
    dispatch(actionCreators.getMergeFieldOperation(dbType,params));
  },
  getMergeColumnFamily(id,database){
    dispatch(actionCreators.getMergeColumnFamilyOperation(id,database));
  },
  clearMergeField(){
    dispatch(actionCreators.clearMergeFieldOperation());
  },
})

export default connect(mapStateToProps, mapDispatchToProps)(FieldMerge);